package com.zhc.tools.demo.web.controller;
   

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.zhc.tools.common.util.DateHelper;
import com.zhc.tools.core.fileimport.StrategyContext;
import com.zhc.tools.core.fileimport.domain.FileStrategySetting;
import com.zhc.tools.core.fileimport.domain.ImportFileResultEnum;
import com.zhc.tools.core.fileimport.domain.ImportLogObject;
import com.zhc.tools.core.fileimport.service.IBaseUploadFile;
import com.zhc.tools.demo.web.controller.base.BaseController;

/**
 * ImportFileController ：批量修改导入file
 * 
 * @author zhc
*/
@Controller
@RequestMapping("importFile")
public class ImportFileController extends BaseController {

    /** 视图前缀 */
    private static final String viewPrefix ="importFile";
    
    @Resource(name = "baseUploadFileService")
    private IBaseUploadFile baseUploadFileService;
    
    /***
     * 显示导入页面
     * @return
     */
    @RequestMapping(value = "/upload-page")
    public String uploadPage(Model model, String groupType){
    	if (StringUtils.isNotBlank(groupType)) {
    		model.addAttribute("fileStrategySettings", this.baseUploadFileService.getFileStrategySettingsByGropyType(groupType));
    	}
    	model.addAttribute("groupType", groupType);
    	return viewPrefix + "/upload-page";
    }
    
    /**
     * 文件上传方法
     * @return
     */
    @RequestMapping(value = "/upload")
    public String upload(@RequestParam(value = "uploadfile", required = false) MultipartFile uploadfile, 
    						StrategyContext strategyContext, Model model){
    	
		//结果列表
		try {
			Long loginUserId = 999L;
//			Long loginUserId = getLoginUserId();
			
			String filename = uploadfile.getOriginalFilename();
			
			strategyContext.setFilename(filename);
			// 设置导入批次
			
			boolean result = false;
			boolean isContinue = true;
			if (loginUserId == null || loginUserId <= 0) {
				// 验证登录人信息
				strategyContext.setCodeByResultEnum(ImportFileResultEnum.NO_PERMISSION_ERROR);
				isContinue = false;
			} else if (StringUtils.isBlank(filename)) {
				// 验证导入文件名信息
				strategyContext.setCodeByResultEnum(ImportFileResultEnum.NOT_FOUND_FILENAME_ERROR);
				isContinue = false;
			} else if (strategyContext == null 
					|| strategyContext.getFileStrategySetting() == null 
					|| StringUtils.isBlank(strategyContext.getFileStrategySetting().getGroupType())
					|| StringUtils.isBlank(strategyContext.getFileStrategySetting().getStrategyServiceType())) {
				// 验证操作类别信息
				strategyContext.setCodeByResultEnum(ImportFileResultEnum.NOT_FOUND_TYPE_ERROR);
				isContinue = false;
			}
			FileStrategySetting fileStrategySetting = this.baseUploadFileService.getFileStrategy(strategyContext.getFileStrategySetting());
			if (fileStrategySetting == null) {
				// 验证操作类别信息
				strategyContext.setCodeByResultEnum(ImportFileResultEnum.NOT_FOUND_TYPE_ERROR);
				isContinue = false;
			} else if (fileStrategySetting.isValidFilename() && (StringUtils.isBlank(fileStrategySetting.getStrategyName())
								|| !filename.startsWith(fileStrategySetting.getStrategyName()))) {
				// 导入文件名不合规范
				strategyContext.setCodeByResultEnum(ImportFileResultEnum.NOT_STANDARD_FILENAME_ERROR, 
						String.format("导入文件名称不合规范，导入【%s】类别必须以【%s】开头！", fileStrategySetting.getStrategyName(), fileStrategySetting.getStrategyName()));
				isContinue = false;
			}
			
			if (isContinue) {
				strategyContext.setFileStrategySetting(fileStrategySetting);
				strategyContext.setBatch(fileStrategySetting.getGroupType() + "_" + fileStrategySetting.getStrategyServiceType() + "_" + DateHelper.getCurrentDateStr("yyyyMMddHHmmssSSS"));
				strategyContext.setInputStream(uploadfile.getInputStream());
				strategyContext.setCreateUserId(loginUserId);
				strategyContext.setCreateUser(getLoginUserName());
				
				strategyContext.putPreDataMap("test", "test");
				
				result = strategyContext.doExecute();

				List<ImportLogObject> dataList = strategyContext.getImportLogObjects();

				if (dataList != null && dataList.size() > 0) {
					Collections.sort(dataList, new Comparator<ImportLogObject>() {

						@Override
						public int compare(ImportLogObject o1, ImportLogObject o2) {
							if (o1 != null && o2 != null && o1.getStatus() != null && o2.getStatus() != null) {
								return o1.getExcelNo() - o2.getExcelNo();
							}
							return 0;
						}
					});
					Collections.sort(dataList, new Comparator<ImportLogObject>() {

						@Override
						public int compare(ImportLogObject o1, ImportLogObject o2) {
							if (o1 != null && o2 != null && o1.getStatus() != null && o2.getStatus() != null) {
								return o1.getStatus() - o2.getStatus();
							}
							return 0;
						}
					});
				}				
			}
			
			//3.返回结果页面
			model.addAttribute("flag", result);
			model.addAttribute("strategyContext", strategyContext);
			
		} catch (Exception e) {
			logger.error("ImportFileController#upload read readFile Exception :", e);
		}
		return viewPrefix + "/upload-result";
    }
}
